package jp.michi.makimono;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.math.BigDecimal;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.BitmapFactory.Options;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;
import android.view.Window;
import android.view.SurfaceHolder.Callback;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CopyOfBookActivity extends Activity {
    SurfaceHolder holder;
    int index = 0;
    TextView console;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        console = new TextView(this);
        SurfaceView surfaceView = new SurfaceView(this);
        surfaceView.getHolder().addCallback(new Callback() {
            public void surfaceCreated(SurfaceHolder holder) {
                CopyOfBookActivity.this.holder = holder;
            }
            public void surfaceDestroyed(SurfaceHolder holder) {}
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
        });
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.addView(console, ViewGroup.LayoutParams.FILL_PARENT);
        layout.addView(surfaceView, ViewGroup.LayoutParams.WRAP_CONTENT);
        setContentView(layout);
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        try {
            StringBuilder builder = new StringBuilder();
            if (event.getAction() == MotionEvent.ACTION_UP) {
                String filePath = "/sdcard/_my/test/";
                String[] books = {"p57x43.jpg", "p113x85.jpg", "p228x171.jpg", "p456x342.jpg", "p912x684.jpg", "p1824x1368.jpg", "p3648x2736.jpg"};
                //                for (String book : books) {
                long start = System.nanoTime();
                //                builder.append("index " + index);
                builder.append("setup " + BigDecimal.valueOf(System.nanoTime() - start).movePointLeft(6));
                start = System.nanoTime();
                //                options.inJustDecodeBounds = false;
                //                options.inSampleSize = 1;
                //                options.inPreferredConfig = Config.RGB_565;
                //                InputStream stream = getAssets().open(books[index]);
                RandomAccessFile randomAccessFile = new RandomAccessFile(filePath + books[index], "r");
                //                Rect rect = new Rect(0, 0, 100, 100);
                Options options = new Options();
                options.inInputShareable = true;
                options.inPurgeable = true;
                Bitmap bitmap = BitmapFactory.decodeFileDescriptor(randomAccessFile.getFD(), null, options);
                builder.append("\nsize " + options.outWidth + "x" + options.outHeight);
                //                builder.append("\nsize " + bitmap.getWidth() + "x" + bitmap.getHeight());
                builder.append("\ndecodeFile " + BigDecimal.valueOf(System.nanoTime() - start).movePointLeft(6));
                start = System.nanoTime();
                //                canvas.drawBitmap(bitmap, -options.outWidth / 4, -options.outHeight / 4, paint);
                float zoom = (float) getResources().getDisplayMetrics().widthPixels / (float) options.outWidth;
                //                {
                //                    canvas.scale(zoom * 3, zoom * 3);
                //                    canvas.drawBitmap(bitmap, 0, 0, paint);
                //                }
                //                {
                //                    ResizableBitmap resizableBitmap = new ResizableBitmap(bitmap);
                //                    resizableBitmap.resize((3 * zoom * options.outWidth), (3 * zoom * options.outHeight));
                //                    resizableBitmap.draw(canvas);
                //                }
                //                {
                //                    Bitmap zoomBitmap = Bitmap.createScaledBitmap(bitmap, (int) (4 * zoom * options.outWidth), (int) (4 * zoom * options.outHeight), false);
                //                    canvas.drawBitmap(zoomBitmap, 0, 0, paint);
                //                    zoomBitmap.recycle();
                //                }
                {
                    Paint paint = new Paint();
                    paint.setFilterBitmap(true);
                    Matrix matrix = new Matrix();
                    matrix.setScale(zoom, zoom);
                    Canvas canvas = holder.lockCanvas();
                    canvas.drawBitmap(bitmap, matrix, paint);
                    holder.unlockCanvasAndPost(canvas);
                }
                //                {
                //                    canvas.drawBitmap(bitmap,//
                //                            new Rect(0, 0, options.outWidth, options.outHeight),
                //                            new RectF(0, 0, 4 * zoom * options.outWidth, 4 * zoom * options.outHeight),
                //                            paint);
                //                }
                bitmap.recycle();
                randomAccessFile.close();
                builder.append("\ndrawBitmap " + BigDecimal.valueOf(System.nanoTime() - start).movePointLeft(6));
                //                builder.append("\n");
                Log.v("test", builder.toString());
                //                }
                console.setText(builder);
                if (index >= books.length - 1) {
                    index = 0;
                } else {
                    index++;
                }
            }
            return true;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        try {
            long start = System.nanoTime();
            Mipmap.prepare("/sdcard/_my/test/page.jpg");
            console.setText("Mipmap prepare time = " + BigDecimal.valueOf(System.nanoTime() - start).movePointLeft(6));
            String createdFile = "/sdcard/_my/test/tmp.jpg";
            //
            RandomAccessFile randomAccessFile = new RandomAccessFile(createdFile, "r");
            Options options = new Options();
            options.inInputShareable = true;
            options.inPurgeable = true;
            Bitmap bitmap = BitmapFactory.decodeFileDescriptor(randomAccessFile.getFD(), null, options);
            Paint paint = new Paint();
            //            paint.setFilterBitmap(true);
            Matrix matrix = new Matrix();
            //            float zoom = (float) getResources().getDisplayMetrics().widthPixels / (float) options.outWidth;
            //            matrix.setScale(zoom, zoom);
            Canvas canvas = holder.lockCanvas();
            canvas.drawBitmap(bitmap, matrix, paint);
            holder.unlockCanvasAndPost(canvas);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    }
}
